package utils

import "time"

// UnixMilliToZeroHour 毫秒级时间戳转换为每日凌晨时间戳
func UnixMilliToZeroHour(timestamp int64, zone string) (int64, error) {
	lo, err := time.LoadLocation(zone)
	if err != nil {
		return timestamp, err
	}
	t0 := time.UnixMilli(timestamp).In(lo).Format(time.DateOnly)

	tt, err := time.ParseInLocation(time.DateOnly, t0, lo)
	return tt.UnixMilli(), err
}

// UnixMilliToMonth 毫秒级时间戳转换为每月1号凌晨时间戳
func UnixMilliToMonth(timestamp int64, zone string) (int64, error) {
	lo, err := time.LoadLocation(zone)
	if err != nil {
		return timestamp, err
	}
	tm := time.UnixMilli(timestamp).In(lo)
	return time.Date(tm.Year(), tm.Month(), 1, 0, 0, 0, 0, time.Local).UnixMilli(), nil
}

// UnixMilliToYear 毫秒级时间戳转换为每年1月1号凌晨时间戳
func UnixMilliToYear(timestamp int64, zone string) (int64, error) {
	lo, err := time.LoadLocation(zone)
	if err != nil {
		return timestamp, err
	}
	tm := time.UnixMilli(timestamp).In(lo)
	return time.Date(tm.Year(), 1, 1, 0, 0, 0, 0, time.Local).UnixMilli(), nil
}

// UnixMilliFixUnit 毫秒级时间戳按unit取整
func UnixMilliFixUnit(timestamp int64, unit int64) int64 {
	return timestamp - timestamp%unit
}
